package com.atguigu.tingshu.order.strategy.impl;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.strategy.OrderBuildStrategy;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * VIP订单构建策略
 */
@Slf4j
@Component
public class VipOrderBuildStrategy implements OrderBuildStrategy {

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public OrderInfoVo buildOrderInfo(TradeVo tradeVo, Long userId) {
        log.info("构建VIP订单信息 - vipId: {}", tradeVo.getItemId());

        // 1. 查询VIP套餐信息
        VipServiceConfig vipServiceConfig = userFeignClient.getVipServiceConfig(tradeVo.getItemId()).getData();

        // 2. 构建OrderInfoVo
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        orderInfoVo.setItemType(SystemConstant.ORDER_ITEM_TYPE_VIP);

        // 3. 构建VIP订单明细
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setItemId(vipServiceConfig.getId());
        orderDetailVo.setItemName(vipServiceConfig.getName());
        orderDetailVo.setItemUrl(vipServiceConfig.getImageUrl());
        orderDetailVo.setItemPrice(vipServiceConfig.getDiscountPrice());

        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        orderDetailVoList.add(orderDetailVo);
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);

        // 4. 计算订单金额
        BigDecimal originalAmount = vipServiceConfig.getPrice();
        BigDecimal orderAmount = vipServiceConfig.getDiscountPrice();
        BigDecimal derateAmount = originalAmount.subtract(orderAmount);

        orderInfoVo.setOriginalAmount(originalAmount);
        orderInfoVo.setDerateAmount(derateAmount);
        orderInfoVo.setOrderAmount(orderAmount);

        // 5. 订单减免明细列表
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();
        if (derateAmount.compareTo(BigDecimal.ZERO) > 0) {
            OrderDerateVo orderDerateVo = new OrderDerateVo();
            orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT);
            orderDerateVo.setDerateAmount(derateAmount);
            orderDerateVo.setRemarks("VIP服务折扣");
            orderDerateVoList.add(orderDerateVo);
        }
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);

        log.info("VIP订单信息构建完成 - orderAmount: {}", orderAmount);
        return orderInfoVo;
    }

    @Override
    public String getOrderType() {
        return SystemConstant.ORDER_ITEM_TYPE_VIP;
    }
}
